package com.solution.admin.auth.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.crypto.hash.SimpleHash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.solution.admin.auth.constants.AuthConstants;
import com.solution.admin.auth.entity.RoleEntity;
import com.solution.admin.auth.entity.UserEntity;
import com.solution.admin.auth.service.RoleService;
import com.solution.admin.auth.service.UserService;
import com.solution.common.controller.BaseController;
import com.solution.common.entity.BaseReturn;
import com.solution.common.page.JSONGrid;
import com.solution.common.page.LayuiConstants;
import com.solution.common.page.LayuiJSONGrid;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;
import com.solution.common.utils.string.StringUtil;

/**
 * 用户web控制层
 * @author llp
 * @date 2017年4月8日 上午11:09:10
 */
@RequestMapping("/user")
@Controller
public class UserController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private UserService userService;
	
	@Autowired
	private RoleService roleService;
	
	/**
	 * 跳转用户列表页面
	 * @param request
	 * @return
	 * @author james
	 */
	@RequestMapping("/toUserList")
	public String toUserList(HttpServletRequest request){
		return "/auth/user_list";
	}
	

	/**
	 * 分页查询用户列表
	 */
	@RequestMapping("/listUserPage")
	@ResponseBody
	public LayuiJSONGrid getUserList(UserEntity user, HttpServletRequest request){
		int pageNum=Integer.parseInt(request.getParameter("page"));
		int numPerPage=Integer.parseInt(request.getParameter("limit"));
		PageParam pageParam = super.getPageParam(request);
		pageParam.setPageNum(pageNum);
		pageParam.setNumPerPage(numPerPage);
		// 封装参数
		String status = request.getParameter("status");
		String roleId = request.getParameter("roleId");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("userName", user.getUserName());
		paramMap.put("userCode", user.getUserCode());
		paramMap.put("mobile", user.getMobile());
		paramMap.put("roleId", roleId);
		if (StringUtil.isNotNull(status) && StringUtil.isNotEmpty(status)) {
			paramMap.put("status", status);
			user.setStatus(Integer.parseInt(status));
		} else {
			user.setStatus(3);
		}
		if (StringUtil.isNotNull(user.getOrgId()) && StringUtil.isNotEmpty(user.getOrgId())) {
            paramMap.put("orgId", user.getOrgId());
        }
		try {
			PageBean pageBean = userService.listUser(pageParam, paramMap);
			return new LayuiJSONGrid(LayuiConstants.SUCCESS,LayuiConstants.SUC_MSG,pageBean.getTotalCount(), pageBean.getRecordList());
		} catch (Exception e) {
			handleException("分页查询用户", logger, e);
		}
		return new LayuiJSONGrid();
	}
	
	
	/**
	 * 跳转业务员选择器
	 */
	@RequestMapping("/toSalesmanSelector")
	public String toSalesmanSelector(UserEntity user, HttpServletRequest request) {
		return "/coupon/salesman_selector";
	}
	
	/**
	 * 查询业务员列表(选择器)
	 * @author james
	 */
	@RequestMapping("/listSalesmanForSelector")
	@ResponseBody
	public List<UserEntity> listSalesmanForSelector(HttpServletRequest request){
		Map<String, Object> paramMap = new HashMap<String, Object>();
		List<UserEntity> salesmanList = userService.listSalesmanForSelector(paramMap);
		return salesmanList;
	}
	
	/**
	 * 检查用户是否存在
	 * @param request
	 * @return
	 */
	@RequestMapping("/existsUniqueUser")
	@ResponseBody
	public String dluserUniqueCheck(HttpServletRequest request) {
		// 新增和修改时的校验重复性是不是样的
		String userId = request.getParameter("userId");
		String userCode = request.getParameter("userCode");
		String mobile = request.getParameter("mobile");
		
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("id", userId);
		param.put("userCode", userCode);
		param.put("mobile", mobile);
		int num = userService.checkUserUnique(param);
		
		return num>0?"false":"true";
	}

	/**
	 * 跳转新增用户页面
	 * @author james
	 */
	@RequestMapping("/toAddUser")
	public String toAddUser(HttpServletRequest request) {
		return "auth/user_form";
	}

	/**
	 * 跳转编辑用户页面
	 * @return string 跳转页面路径
	 * @author llp
	 * @date 2017年4月12日 下午2:39:44
	 */
	@RequestMapping("/toUpdateUser")
	public String toUpdateUser(HttpServletRequest request) {
		long id = Long.valueOf(request.getParameter("id"));
		try {
			UserEntity user = userService.getUserById(id);
			request.setAttribute("user", user);
		} catch (Exception e) {
			handleException("跳转编辑用户页面错误", logger, e);
		}
		return "auth/user_form";
	}

	/**
	 * 跳转用户角色分配界面
	 * 
	 * @return string 跳转页面路径
	 * @author llp
	 * @date 2017年4月12日 下午2:39:44
	 */
	@RequestMapping("/toAssginUserRole")
	public String toAssginUserRole(HttpServletRequest request) {
		long userId = Long.valueOf(request.getParameter("id"));
		UserEntity user = userService.getUserById(userId);
		request.setAttribute("user", user);
		// 查询所有角色
		List<RoleEntity> roleList = roleService.listRoleWithChkflagForUser(userId);
		request.setAttribute("roleList", roleList);
		return "auth/user/user_role_settings";
	}

	/**
	 * 分配用户角色
	 * @return string 跳转页面路径
	 * @author llp
	 * @date 2017年4月12日 下午2:39:44
	 */
	@RequestMapping("/assginUserRole")
	@ResponseBody
	public Map<String, String> assginUserRole(HttpServletRequest request) {
		Map<String, String> result = new HashMap<String, String>();
		// 系统ids
		String[] roleIds = request.getParameter("roleIds").split(",");
		long userId = Long.valueOf(request.getParameter("userId"));
		if (roleIds != null) {
			if (roleIds.length > 0) {
				ArrayList<Long> roleIdList = new ArrayList<Long>();
				for (int i = 0; i < roleIds.length; i++) {
					String strRoleId = roleIds[i];
					if (StringUtil.isNotNull(strRoleId) && StringUtil.isNotEmpty(strRoleId)) {
						Long roleId = Long.parseLong(strRoleId);
						if (roleId > 0) {
							roleIdList.add(roleId);
						}
					}

				}
				try {
					// 设置用户角色
					userService.assginUserRole(userId, roleIdList);
					result.put("resultCode", "1");
					result.put("resultMsg", "设置用户角色成功");
				} catch (Exception e) {
					handleException("设置用户角色失败", logger, e);
					result.put("resultCode", "0");
					result.put("resultMsg", "设置用户角色成功");
				}
			}
		}
		roleIds = null;
		return result;
	}
	
	
	/**
	 * 修改用户信息
	 * @author james
	 */
	@RequestMapping("/saveOrUpdateUser")
	@ResponseBody
	public Map<String, String> saveOrUpdateUser(UserEntity user,HttpServletRequest request) {
		Map<String, String> resultMap = new HashMap<String, String>();
		try {
			int result = 0;
			if(user.getId() != null){
				user.setModifier(getUserCode());
				user.setModifyTime(new Date());
				result = userService.updateUser(user);
			}else{
				user.setStatus(1);
				user.setIsDelete(1);
				user.setPassword("123456");
				user.setCreater(getUserCode());
				user.setCreateTime(new Date());
				long uid = userService.saveUser(user);
				result = (int)uid;
			}
			syncSuccessReslt(resultMap, result);
		} catch (Exception e) {
			handleException("修改用户", logger, e);
			syncErrorReslt(resultMap);
		}
		return resultMap;
	}
	
	/**
	 * 重置用户密码
	 * 
	 * @param userEntity
	 *            用户实体
	 * @return 页面视图
	 * @author llp
	 * @date 2017年4月12日 下午1:52:29
	 */
	@RequestMapping("/resetUserPwd")
	@ResponseBody
	public Map<String, String> resetUserPwd(HttpServletRequest request) {
		Map<String, String> result = new HashMap<String, String>();
		String id = request.getParameter("id");
		Long userId = Long.valueOf(id);
		// 传入用户代码是为了更新密码后，清空对应在redis缓存
		String userCode = request.getParameter("userCode");
		try {
			userService.resetUserPwd(userId, userCode);
			result.put("resultCode", "1");
			result.put("resultMsg", "用户密码已重置为123456！");
		} catch (Exception e) {
			handleException("重置用户密码失败", logger, e);
			result.put("resultCode", "0");
			result.put("resultMsg", "密码重置失败");
		}
		return result;
	}

	/**
	 * 停用用户
	 * @author james
	 */
	@RequestMapping("/disableUser")
	@ResponseBody
	public Map<String, String> disableUser(UserEntity user) {
		Map<String, String> resultMap = new HashMap<String, String>();
		try {
			// 无效用户
			int result = userService.updateStatus(user.getId(), new Integer(0));
			syncSuccessReslt(resultMap, result);
		} catch (Exception e) {
			handleException("停用用户", logger, e);
			syncErrorReslt(resultMap);
		}
		return resultMap;
	}

	/**
	 * 启用用户
	 * @author james
	 */
	@RequestMapping("/enableUser")
	@ResponseBody
	public Map<String, String> enableUser(UserEntity user) {
		Map<String, String> resultMap = new HashMap<String, String>();
		try {
			int result = userService.updateStatus(user.getId(), new Integer(1));
			syncSuccessReslt(resultMap, result);
		} catch (Exception e) {
			handleException("启用用户失败", logger, e);
			syncErrorReslt(resultMap);
		}
		return resultMap;
	}
	
	
	/**
	 * (逻辑)删除用户
	 * @author james
	 */
	@RequestMapping("/deleteUser")
	@ResponseBody
	public Map<String, String> deleteUser(UserEntity user) {
		Map<String, String> resultMap = new HashMap<String, String>();
		try {
			int result = userService.logicDeleteUser(user.getId());
			syncSuccessReslt(resultMap, result);
		} catch (Exception e) {
			handleException("删除用户", logger, e);
			syncErrorReslt(resultMap);
		}
		return resultMap;
	}
	
	
	/**
	 * 跳转修改密码页面
	 * @param request
	 * @return
	 * @author qiaoenyin
	 * @date 2017年6月19日 下午3:56:14
	 */
	@RequestMapping("/toModifyPwd")
	public String toModifyPwd(HttpServletRequest request) {
		return "auth/user/modifyPwd";
	}
	
	/**
	 * 修改登录人密码
	 * @param request
	 * @return
	 * @author qiaoenyin
	 * @date 2017年6月19日 下午3:56:31
	 */
	@RequestMapping("/modifyPwd")
	@ResponseBody
	public Map<String, String> modifyPwd(HttpServletRequest request) {
		Map<String, String> result = new HashMap<String, String>();
		try {
			String oldPassword = request.getParameter("oldPassword");
			String newPassword = request.getParameter("newPassword");
			UserEntity user = userService.getUserById(getUserId());
			String passwordSalt=user.getPasswordSalt();
			String password =user.getPassword();
			Object simpleHash = new SimpleHash("MD5", oldPassword,passwordSalt,1);
			if(password.equals(String.valueOf(simpleHash))){
				user.setPassword(newPassword);
				user.setId(getUserId());
				long res = userService.updatePwd(user);
				if(res == 1){
					result.put("resultCode", "1");
					result.put("resultMsg", "修改成功");
				}else{
					result.put("resultCode", "0");
					result.put("resultMsg", "修改失败");
				}
			}else{
				result.put("resultCode", "-1");
				result.put("resultMsg", "原密码错误，修改失败");
			}
		} catch (Exception e) {
			handleException("修改失败", logger, e);
			result.put("resultCode", "0");
			result.put("resultMsg", "修改失败");
		}
		return result;
	}
	
	/**
	 * 根据orgId查询uesrlist
	 * @author benqingsong
	 * @date 2017年8月9日 下午3:07:56
	 * @param request
	 * @param orgId
	 * @return
	 */
	@RequestMapping("/queryListUserByOrgId")
	@ResponseBody
	public BaseReturn  queryListUserByOrgId(HttpServletRequest request) {
		BaseReturn baseReturn = new  BaseReturn();
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("orgId", request.getParameter("orgId"));
		List<UserEntity> UserEntity=userService.getUserList(param);
		if(UserEntity.size()>0){
			baseReturn.setData(UserEntity);
			baseReturn.setSuccess(1);
			baseReturn.setMsg("查询下拉信息成功");
		}else {
			baseReturn.setSuccess(-1);
			baseReturn.setMsg("查询下拉信息失败");
		}
		return baseReturn;
	}
	
	/**
	 * 获取业务员列表数据
	 * @param user
	 * @param request
	 * @return
	 * @author: solin
	 * @date: 2017年10月20日 下午4:05:46
	 */
	@RequestMapping("/getSalesmanList")
	@ResponseBody
	public List<UserEntity> getSalesmanList(String roleId, HttpServletRequest request){
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("roleId", roleId);
		return userService.getSalesmanList(param);
	}
}
